/*
 * Copyright 2012 Gregor Schauer
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package at.schauer.gregor.vienna.serializer.plugin;

import at.schauer.gregor.vienna.context.ViennaContext;
import at.schauer.gregor.vienna.context.ViennaContextAware;
import at.schauer.gregor.vienna.convert.provider.ConverterProvider;
import at.schauer.gregor.vienna.convert.vienna.SimpleConverter;
import at.schauer.gregor.vienna.serializer.Serializer;
import at.schauer.gregor.vienna.util.ViennaUtils;
import org.apache.commons.lang3.ClassUtils;

import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author Gregor Schauer
 */
public class ToStringSerializerPlugin<T> extends DefaultSerializerPlugin<T> implements ViennaContextAware {
	private static final Pattern SEPARATOR_PATTERN = Pattern.compile(Serializer.CLASS_OBJECT_SEPARATOR);
	private ViennaContext ctx;

	@Override
	@SuppressWarnings("unchecked")
	public <E extends T> E postConstruct(Map<String, Object> map, E obj) {
		ConverterProvider<SimpleConverter> converterProvider = (ConverterProvider<SimpleConverter>) ctx.getConverterProvider(obj.getClass());
		for (Map.Entry<String, Object> entry : map.entrySet()) {
			if (entry.getValue() != null) {
				try {
					String[] value = SEPARATOR_PATTERN.split((CharSequence) entry.getValue(), 2);
					Class<?> type = ClassUtils.getClass(value[0]);
					map.put(entry.getKey(), converterProvider.convert(value[1], type));
				} catch (ClassNotFoundException e) {
					throw new RuntimeException(e);
				}
			}
		}
		return obj;
	}

	@Override
	@SuppressWarnings("unchecked")
	public Map<String, Object> postDeconstruct(Map<String, Object> map, T obj) {
		for (Map.Entry<String, Object> entry : map.entrySet()) {
			if (entry.getValue() != null) {
				Class<?> type = entry.getValue().getClass();
				map.put(entry.getKey(), type.getName() + Serializer.CLASS_OBJECT_SEPARATOR + ViennaUtils.SerializationUtils.save(ctx, entry.getValue()));
			}
		}
		return map;
	}

	@Override
	public void setViennaContext(ViennaContext viennaContext) {
		this.ctx = viennaContext;
	}
}
